layui.use(['form', 'element', 'miniPage', 'utils', 'upload', 'laytpl', 'xmSelect', 'laydate'], function () {
    var $ = layui.jquery,
        layer = layui.layer,
        form = layui.form,
        element = layui.element,
        miniPage = layui.miniPage,
        utils = layui.utils,
        laytpl = layui.laytpl,
        upload = layui.upload,
        xmSelect = layui.xmSelect,
        laydate = layui.laydate;

    // 当前弹出层，防止ID被覆盖
    var parentIndex = layer.index;

    /**
     *  定义模板
     */
    var tplTalentPanel = $('#tplTalentPanel').html(); //添加候选人容器
    var tplTalent = $('#tplTalent').html(); //候选人
    var tplChargePanel = $('#tplChargePanel').html(); //收费信息容器
    var tplCharge = $('#tplCharge').html();

    /**
     *  定义组件
     */
    // 候选人
    Vue.component('talentPanel', {
        template: tplTalentPanel,
        methods: {
            handleAddBtnClick: function () {
                this.$emit('add'); // 触发父组件定义的事件
            }
        }
    });
    Vue.component('talentItem', {
        template: tplTalent,
        props: {
            data: {
                type: Object,
                default: function () {
                    return {}
                }
            },
            deleteable: {
                type: Boolean,
                default: true
            },
            talent: {
                type: Array,
                default: function () {
                    return []
                }
            }
        },
        data: function () {
            return {
                form: {
                    id: '',
                    talentId: '',
                    expectedEntryTime: '',
                    guaranteePeriod: '',
                    isNew: false
                },
                xmSelectItem: null
            }
        },
        mounted: function () {
            this.getData();
            this.xmSelectItem = this.initTalent();
            if (this.talent.length) {
                this.updateTalent(this.talent)
            }

            this.entryTime();
        },
        watch: {
            data: {
                handler: function (value) {
                    if (value) {
                        utils.copyObject(this.form, value)
                    }
                },
                immediate: true
            },
            talent: {
                handler: function (value) {
                    if (!this.xmSelectItem) {
                        return
                    }
                    if (Array.isArray(value) && value.length) {
                        this.updateTalent(value, this.form.talentId)
                    }
                }
            }
        },
        methods: {
            getData: function () {
                var obj = {};
                var newIgnoreKey = ['id', 'isNew'];
                var ignoreKey = ['isNew'];
                if (this.form.isNew) {
                    utils.copyObjectWithIgnoreKey(obj, this.form, newIgnoreKey)
                } else {
                    utils.copyObjectWithIgnoreKey(obj, this.form, ignoreKey)
                }
                return obj;
            },
            handleDelete: function () {
                this.$emit('delete', this.form.id)
            },
            initTalent: function () {
                var that = this;
                var $talentSelect = that.$refs.talentSelect;
                if (!$talentSelect) {
                    return null
                }
                var xmSelectItem = xmSelect.render({
                    el: $talentSelect,
                    radio: true,
                    clickClose: true,
                    model: {
                        icon: 'hidden'
                    },
                    prop: {
                        name: 'name',
                        value: 'id',
                    },
                    name: 'talentId',
                    theme: {
                        color: '#84d0e8',
                    },
                    filterable: true,
                    data: [],
                    on: function (data) {
                        var arr = data.arr;
                        if (arr.length) {
                            that.form.talentId = arr[0].id;
                        } else {
                            that.form.talentId = '';
                        }
                    }
                });
                return xmSelectItem;
            }, // 候选人
            updateTalent: function (list, val) {
                var initValue = val === undefined ? [] : [val]
                if (this.xmSelectItem) {
                    this.xmSelectItem.update({
                        data: list,
                        initValue: initValue
                    });
                }
            },
            entryTime: function () {
                var that = this;
                var $entryTime = that.$refs.entryTime;
                laydate.render({
                    elem: $entryTime,
                    trigger: 'click',
                    done: function(value, date, endDate){
                        that.expectedEntryTime = value;
                        console.log(value); //得到日期生成的值，如：2017-08-18
                    }
                });
            }, // 预计入职时间
        },
    });
    Vue.component('talentModular', {
        template: '<talent-panel @add="handleAdd">' +
            '   <talent-item ref="talentItem" v-for="item in lists" :key="item.id" :data="item" :talent="talent" :deleteable="lists.length > 1" @delete="handleDelete"></talent-item>' +
            '</talent-panel>',
        props: {
            data: {
                type: Array,
                default: function () {
                    return []
                }
            },
            talent: {
                type: Array,
                default: function () {
                    return []
                }
            }
        }, // 向下传递数据给子组件
        data: function () {
            return {
                lists: []
            }
        },
        watch: {
            data: {
                handler: function (value) {
                    if (value && value.length) {
                        this.lists = value
                    } else {
                        this.lists = [
                            this.createNewItem() //创建新的item
                        ]
                    }
                },
                immediate: true
            }
        },
        methods: {
            createNewItem: function () {
                return {
                    id: utils.generateUUID(),
                    billingTalent: '',
                    expectedEntryTime: '',
                    guaranteePeriod: '',
                    isNew: true
                }
            },
            getData: function () {
                var $item = this.$refs.talentItem;
                var data = [];

                $item.forEach(function (item) {
                    data.push(item.getData())
                });
                return data;
            }, // 获取数据
            handleAdd: function () {
                var that = this;
                var item = this.createNewItem();
                that.lists.push(item);
                that.$nextTick(function () {
                    form.render();
                })
            },
            handleDelete: function (id) {
                for (var index = 0; index < this.lists.length; index++) {
                    if (this.lists[index].id === id) {
                        this.lists.splice(index, 1);
                        return
                    }
                }
            }
        }
    });

    // 收费信息
    Vue.component('chargePanel', {
        template: tplChargePanel,
        methods: {
            handleAddBtnClick: function () {
                this.$emit('add');
            }
        }
    });
    Vue.component('chargeItem', {
        template: tplCharge,
        props: {
            data: {
                type: Object,
                default: function () {
                    return {}
                }
            },
            deleteable: {
                type: Boolean,
                default: true
            }
        },
        data: function () {
            return {
                form: {
                    id: '',
                    chargeType: '',
                    incomeAmount: '',
                    expAmount: '',
                    supplier: '',
                    isNew: false
                },
                xmSelectItem: null
            }
        },
        mounted: function () {
            this.getData();

            this.getChargeTypeData();
            this.getSupplierData();

        },
        watch: {
            data: {
                handler: function (value) {
                    if (value) {
                        utils.copyObject(this.form, value)
                    }
                },
                immediate: true
            }
        },
        methods: {
            getData: function () {
                var obj = {};
                var newIgnoreKey = ['id', 'isNew'];
                var ignoreKey = ['isNew'];
                if (this.form.isNew) {
                    utils.copyObjectWithIgnoreKey(obj, this.form, newIgnoreKey)
                } else {
                    utils.copyObjectWithIgnoreKey(obj, this.form, ignoreKey)
                }
                return obj;
            },
            handleDelete: function () {
                this.$emit('delete', this.form.id)
            },
            initChargeType: function () {
                var that = this;
                var $chargeTypeSelect = that.$refs.chargeTypeSelect;
                if (!$chargeTypeSelect) {
                    return null
                }
                var xmSelectItem = xmSelect.render({
                    el: $chargeTypeSelect,
                    radio: true,
                    clickClose: true,
                    model: {
                        icon: 'hidden'
                    },
                    prop: {
                        name: 'name',
                        value: 'id',
                    },
                    name: 'chargeType',
                    theme: {
                        color: '#84d0e8',
                    },
                    filterable: true,
                    data: [],
                    on: function (data) {
                        var arr = data.arr;
                        if (arr.length) {
                            that.form.chargeType = arr[0].id;
                        } else {
                            that.form.chargeType = '';
                        }
                    }
                });
                return xmSelectItem;
            },
            getChargeTypeData: function (val) {
                var that = this;
                utils.Ajax({
                    url: 'api/finance/2_shoufeileixing.json',
                    dataType: 'json',
                    type: 'post',
                    data: {},
                    success: function (response) {
                        var list = response.data.chargeType;
                        if (Array.isArray(list)) {
                            var initValue = val === undefined ? [] : [val];
                            that.initChargeType().update({
                                data: list,
                                initValue: initValue
                            });
                        }
                    }
                });
            }, // 类型
            initSupplier: function () {
                var that = this;
                var $supplierSelect = that.$refs.supplierSelect;
                if (!$supplierSelect) {
                    return null
                }
                var xmSelectItem = xmSelect.render({
                    el: $supplierSelect,
                    radio: true,
                    clickClose: true,
                    model: {
                        icon: 'hidden'
                    },
                    prop: {
                        name: 'name',
                        value: 'id',
                    },
                    name: 'chargeType',
                    theme: {
                        color: '#84d0e8',
                    },
                    filterable: true,
                    data: [],
                    on: function (data) {
                        var arr = data.arr;
                        if (arr.length) {
                            that.form.supplier = arr[0].id;
                        } else {
                            that.form.supplier = '';
                        }
                    }
                });
                return xmSelectItem;
            },
            getSupplierData: function (val) {
                var that = this;
                utils.Ajax({
                    url: 'api/finance/2_gongyingshang.json',
                    dataType: 'json',
                    type: 'post',
                    data: {},
                    success: function (response) {
                        var list = response.data.supplier;
                        if (Array.isArray(list)) {
                            var initValue = val === undefined ? [] : [val];
                            that.initSupplier().update({
                                data: list,
                                initValue: initValue
                            });
                        }
                    }
                });
            }, // 供应商
        },
    });
    Vue.component('chargeModular', {
        template: '<charge-panel @add="handleAdd">' +
            '   <charge-item ref="chargeItem" v-for="item in lists" :key="item.id" :data="item" :deleteable="lists.length > 1" @delete="handleDelete"></charge-item>' +
            '</charge-panel>',
        props: {
            data: {
                type: Array,
                default: function () {
                    return []
                }
            }
        }, // 向下传递数据给子组件
        data: function () {
            return {
                lists: []
            }
        },
        watch: {
            data: {
                handler: function (value) {
                    if (value && value.length) {
                        this.lists = value
                    } else {
                        this.lists = [
                            this.createNewItem() //创建新的item
                        ]
                    }
                },
                immediate: true
            }
        },
        methods: {
            createNewItem: function () {
                return {
                    id: utils.generateUUID(),
                    chargeType: '',
                    incomeAmount: '',
                    expAmount: '',
                    supplier: '',
                    isNew: true
                }
            },
            getData: function () {
                var $item = this.$refs.talentItem;
                var data = [];

                $item.forEach(function (item) {
                    data.push(item.getData())
                });
                return data;
            }, // 获取数据
            handleAdd: function () {
                var that = this;
                var item = this.createNewItem();
                that.lists.push(item);
                that.$nextTick(function () {
                    form.render();
                })
            },
            handleDelete: function (id) {
                for (var index = 0; index < this.lists.length; index++) {
                    if (this.lists[index].id === id) {
                        this.lists.splice(index, 1);
                        return
                    }
                }
            }
        }
    });

    var addBillContent = new Vue({
        el: '#addBillContent',
        data: function () {
            return {
                form: {
                    billingType: 0,
                    projectId: -1, // 项目
                    orderId: -1, // 订单

                    amount: '', // 金额
                    firstPayment: '', // 收款比例
                    lastPayment: '', // 尾款比例
                    invoiceType: '', // invoiceType
                    chargeNotes: '', // 收费备注

                    paymentId: '', // 付款信息

                    PO: '',
                    courierNo: '', // 快递单号
                    courierCompany: '', // 快递公司
                    paymentTerms: '', // Payment Terms
                    invoiceNo: '', // 税务发票号
                    printStatus: 0, // 打印状态
                    payStatus: 0, // 收款状态
                    submitBilling: false, //submit To Billing
                },
                talentList: [], // 候选人列表
                talentInfoList: [],
                chargeInfoList: [], // 收费列表

                fileList: [], // 附件
                payInfo: {
                    type: ''
                }
            }
        },
        mounted: function () {
            this.getInfo();
            this.getFileList();
        },
        methods: {
            getInfo: function () {
                var that = this;
                utils.Ajax({
                    url: 'api/finance/1_bill.json',
                    dataType: 'json',
                    contentType: 'application/json',
                    type: 'get',
                    data: {id: window.userId},
                    success: function (response) {
                        var data = response.data;

                        utils.copySelfObject(that.form, data); //基础表单

                        // console.log(that.form)

                        that.talentInfoList = data.talentInfoList; //候选人信息列表
                        that.chargeInfoList = data.chargeInfoList; //收费信息列表

                        // 重新渲染表单
                        that.initForm();
                    }
                })
            },
            initForm: function () {
                var that = this;

                that.getProjectData(that.form.projectId); // 项目
                that.getOrderData();

                that.getPaymentData(that.form.paymentId); // 客户信息


                form.render();

                element.render();

                // 开票类型
                form.on('radio(billingType)', function (data) {
                    that.form.billingType = data.value;
                    if (data.value == 0) {
                        that.getProjectData();
                    } else if (data.value == 1) {
                        that.getOrderData();
                    }
                });

                // 上传
                upload.render({
                    elem: '#uploadFile',
                    url: 'api/finance/upload_file.json',
                    accept: 'file',
                    before: function (obj) {
                        var _temp = '<div class="layui-progress layui-progress-big mt-10" lay-filter="progress">' +
                            '<div class="layui-progress-bar layui-bg-lightblue"></div>' +
                            '</div>';
                        $('#uploadFile').after(_temp);
                    },
                    progress: function (n, elem) {
                        var percent = n + '%';
                        element.progress('progress', percent);
                    },
                    done: function (res) {
                        if (res.code === 200) {
                            // 移除进度条
                            $('#uploadFile').next('.layui-progress').remove();
                            // 更新列表
                            that.getFileList();
                        }
                    },
                    error: function () {
                        layer.msg('请求错误！');
                    }
                });

                // Payment Terms
                form.on('select(paymentTerms)', function (data) {
                    that.paymentTerms = data.value;
                });


                // submit to billing
                form.on('checkbox(submitBilling)', function (data) {
                    that.submitBilling = data.elem.checked;
                });

                // 检测
                form.on('submit(formDemo)', function (data) {
                    console.log(data.field)
                });
            },
            initProject: function () {
                var that = this;
                var xmSelectItem = xmSelect.render({
                    el: '[lay-event="xm-select-project"]',
                    radio: true,
                    clickClose: true,
                    model: {
                        icon: 'hidden'
                    },
                    prop: {
                        name: 'name',
                        value: 'id',
                    },
                    name: 'projectId',
                    theme: {
                        color: '#84d0e8',
                    },
                    filterable: true,
                    data: [],
                    on: function (data) {
                        var arr = data.arr;
                        if (arr.length) {
                            that.form.projectId = arr[0].id;

                            var config = {
                                type: that.form.billingType,
                                id: that.form.projectId
                            };
                            that.getTalentData(config);
                        } else{
                            that.form.projectId = '';
                        }
                    }
                });
                return xmSelectItem;
            },
            getProjectData: function (val) {
                var that = this;
                utils.Ajax({
                    url: 'api/finance/2_xiangmu.json',
                    dataType: 'json',
                    type: 'post',
                    data: {},
                    success: function (response) {
                        var list = response.data.project;
                        if (Array.isArray(list)) {
                            var initValue = val === undefined ? [] : [val];
                            that.initProject().update({
                                data: list,
                                initValue: initValue
                            });

                            if (val) {
                                var config = {
                                    type: that.form.billingType,
                                    id: that.form.projectId
                                };
                                that.getTalentData(config);
                            }
                        }
                    }
                });
            }, // 项目
            initOrder: function (val) {
                var that = this;
                var xmSelectItem = xmSelect.render({
                    el: '[lay-event="xm-select-order"]',
                    radio: true,
                    clickClose: true,
                    model: {
                        icon: 'hidden'
                    },
                    prop: {
                        name: 'name',
                        value: 'id',
                    },
                    name: 'orderId',
                    theme: {
                        color: '#84d0e8',
                    },
                    filterable: true,
                    initValue: [val],
                    data: [],
                    on: function (data) {
                        var arr = data.arr;
                        if (arr.length) {
                            that.form.orderId = arr[0].id;

                            var config = {
                                type: that.form.billingType,
                                id: that.form.orderId
                            };
                            that.getTalentData(config);
                        } else{
                            that.form.orderId = '';
                        }
                    }
                });
                return xmSelectItem;
            },
            getOrderData: function (val) {
                var that = this;
                utils.Ajax({
                    url: 'api/finance/2_dingdan.json',
                    dataType: 'json',
                    type: 'post',
                    data: {},
                    success: function (response) {
                        var list = response.data.order;
                        if (Array.isArray(list)) {
                            var initValue = val === undefined ? [] : [val];
                            that.initOrder().update({
                                data: list,
                                initValue: initValue
                            });

                            if (val) {
                                var config = {
                                    type: that.form.billingType,
                                    id: val
                                };
                                that.getTalentData(config);
                            }
                        }
                    }
                });
            }, // 订单
            getTalentData: function (config) {
                var that = this;
                utils.Ajax({
                    url: 'api/finance/xm_3.json',
                    dataType: 'json',
                    type: 'post',
                    data: config,
                    success: function (response) {
                        var list = response.data.talent;
                        if (Array.isArray(list)) {
                            that.talentList = list;
                        }
                    }
                });
            }, // 候选人
            initPayment: function () {
                var that = this;
                var xmSelectItem = xmSelect.render({
                    el: '[lay-event="xm-select-payment"]',
                    radio: true,
                    clickClose: true,
                    model: {
                        icon: 'hidden'
                    },
                    prop: {
                        name: 'name',
                        value: 'id',
                    },
                    name: 'paymentId',
                    theme: {
                        color: '#84d0e8',
                    },
                    filterable: true,
                    data: [],
                    on: function (data) {
                        var arr = data.arr;
                        if (arr.length) {
                            that.form.paymentId = arr[0].id;
                            // 客户信息
                            that.getPaymentInfo(that.form.paymentId);
                        } else {
                            that.form.paymentId = '';
                        }
                    }
                });
                return xmSelectItem;
            },
            getPaymentData: function (val) {
                var that = this;
                utils.Ajax({
                    url: 'api/finance/3_fukuanxinxiList.json',
                    dataType: 'json',
                    type: 'post',
                    data: {},
                    success: function (response) {
                        var list = response.data.payment;
                        if (Array.isArray(list)) {
                            var initValue = val === undefined ? [] : [val];
                            that.initPayment().update({
                                data: list,
                                initValue: initValue
                            });
                        }
                    }
                });
            }, // 客户选项
            getPaymentInfo: function (id) {
                var that = this;
                utils.Ajax({
                    url: 'api/finance/3_fukuanxinxiInfo.json',
                    dataType: 'json',
                    type: 'post',
                    data: {id: id},
                    success: function (response) {
                        var data = response.data;
                        utils.copySelfObject(that.payInfo, data);
                    }
                });
            }, // 客户信息
            editPaymentInfo: function () {
                var content = miniPage.getHrefContent('page/finance/public/addBillInfo.html');
                if (content) {
                    layer.open({
                        title: '付款信息',
                        type: 1,
                        shade: 0.2,
                        area: ['100%', '90%'],
                        content: content,
                        btn: ['确认', '取消'],
                        btnAlign: 'c',
                        yes: function (index, layero) {
                            layero.find('[lay-filter="saveBtn"]').click();
                        }
                    });
                }
            },
            getFileList: function () {
                var that = this;
                utils.Ajax({
                    url: 'api/talent_file_list.json',
                    dataType: 'json',
                    contentType: 'application/json',
                    type: 'post',
                    data: '',
                    success: function (response) {
                        var data = response.data;
                        that.fileList = data.fileList;
                    }
                })
            }, // 附件
            addCommas: function (str) {
                return String(str).replace(/(\d)(?=(\d\d\d)+(?!\d))/g, '$1,');
            },
            setXmSingleVal: function (toArr, fromArr) {
                if (fromArr.length) {
                    fromArr.forEach(function (item) {
                        toArr.push(item.id);
                    });
                    return toArr;
                }
            }
        }
    });


});